import { join } from 'node:path'
import fs from 'node:fs'
import { Readability, type ReadabilityResult } from '../src/index.js'
import { load } from 'cheerio'
import { prettyPrint } from './utils.js'
import { fileURLToPath } from 'node:url'

const testPageRoot = fileURLToPath(new URL('./test-pages', import.meta.url))

function generateDebugTestcase(slug: string) {
    const destRoot = join(testPageRoot, slug)

    const dirExists = fs.existsSync(destRoot)
    if (!dirExists) fs.mkdirSync(destRoot)

    const sourceFile = join(destRoot, 'source.html')
    const srcExists = fs.existsSync(sourceFile)

    if (srcExists) {
        const data = fs.readFileSync(sourceFile, { encoding: 'utf-8' })
        runReadability(data, destRoot)
    } else {
        console.log('You should pass a slug of an existing page!')
    }
}

function runReadability(source: string, destRoot: string) {
    const uri = 'http://fakehost/test/page.html'
    const $ = load(source, { baseURI: uri })
    const destPath = join(destRoot, 'debug.html')
    const metadataDestPath = join(destRoot, 'debug-metadata.json')

    // We pass `caption` as a class to check that passing in extra classes works,
    // given that it appears in some of the test documents.
    const reader = new Readability($, {
        classesToPreserve: ['caption'],
        debug: true,
    })
    const result = reader.parse() as Partial<ReadabilityResult>
    const content = prettyPrint(result.content || null)

    if (!content) {
        console.error(
            'No content generated by readability, not going to write expected.html!',
        )
        return
    }

    fs.writeFileSync(destPath, content)

    // Delete the result data we don't care about checking.
    delete result.content
    delete result.textContent
    delete result.length

    fs.writeFileSync(metadataDestPath, JSON.stringify(result, null, 2) + '\n')
}

if (process.argv.length < 3) {
    console.error(
        "Need at least a destination slug and potentially a URL (if the slug doesn't have source).",
    )
    process.exit(0)
}

generateDebugTestcase(process.argv[2] as string)
